#include "TcpServer.hpp"
//#include "Commandexec.hpp"
#include "Protocol.hpp"
#include "Calculator.hpp"
#include "Daemon.hpp"
#include <memory>

//Calculator gcal;

using cal_fun = std::function<Response(const Request& req)>;

class Parseclass
{
public:
    Parseclass(cal_fun cal) : _cal(cal) 
    {}

    std::string Entry(std::string &package)
    {
        // 1.判断报文的完整性
        std::string message;
        std::string respstr;

        while (Decode(package, &message))
        {
            LOG(LogLevel::DEBUG) << "Content: \n" << message;

            if (message.empty())
                break;

            // 2.反序列化，message是一个曾经被序列化的request
            Request req;
            if (!req.Deserialize(message))
                break;

            std::cout << "#################" << std::endl;
            req.Print();
            std::cout << "#################" << std::endl;

            // 3.计算
            Response resp = _cal(req);

            // 4.序列化
            std::string res;
            resp.Serialize(res);
            LOG(LogLevel::DEBUG) << "序列化: \n" << res;

            // 5.添加报头长度字段
            Encode(res);
            LOG(LogLevel::DEBUG) << "Encode: \n" << res;

            // 6.拼接应答
            respstr += res;
        }

        LOG(LogLevel::DEBUG) << "respstr: \n" << respstr;
        return respstr;
    }
private:
    cal_fun _cal;
};



int main()
{
    Daemon(false, false);

    //ENABLE_CONSOLE_LOG();
    ENABLE_FILE_LOG();
    
    // Command cmd;
    // std::unique_ptr<TcpServer> tsvr = std::make_unique<TcpServer>([&cmd](std::string cmdstr){
    //     return cmd.Execute(cmdstr);
    // });

    // 1.计算模块
    Calculator mycal;
    
    // 2.解析对象
    Parseclass myprase([&mycal](const Request& req){
        return mycal.Execute(req);
    });

    // 3.通信模块， 只负责进行IO
    std::unique_ptr<TcpServer> tsvr = std::make_unique<TcpServer>([&myprase](std::string &package){
        return myprase.Entry(package);
    });

    tsvr->InitServer();
    tsvr->Start();


    return 0;
}